package com.lianjinsoft.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.lianjinsoft.mapper.OrderMapper;
import com.lianjinsoft.pojo.Order;
import com.lianjinsoft.service.OrderService;
import com.lianjinsoft.util.LogUtil;

@Service
public class OrderServiceImpl implements OrderService{
	private final String prefix = "order:";
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public void addOrder(Order order) {
		orderMapper.addOrder(order);
		redisTemplate.opsForValue().set(prefix+order.getOrderNo(), order);
		LogUtil.info("新增订单，添加缓存："+order);
	}

	@Override
	public void delOrder(String orderNo) {
		if(redisTemplate.hasKey(prefix+orderNo)){
			redisTemplate.delete(prefix+orderNo);
			LogUtil.info("删除缓存数据："+orderNo);
		}
		orderMapper.delOrder(orderNo);
	}

	@Override
	public void updOrder(Order order) {
		orderMapper.updOrder(order);
		if(redisTemplate.hasKey(prefix+order.getOrderNo())){
			redisTemplate.opsForValue().set(prefix+order.getOrderNo(), order);
			LogUtil.info("更新缓存订单信息："+order);
		}
	}
	
	@Override
	public Order queryOrderByNo(String orderNo) {
		Order order = (Order)redisTemplate.opsForValue().get(prefix+orderNo);
		if(order != null){
			LogUtil.info("从缓存获取数据："+order);
			return order;
		}
		
		order = orderMapper.queryOrderByNo(orderNo);
		LogUtil.info("从数据库获取数据："+order);
		if(order != null){
			redisTemplate.opsForValue().set(prefix+orderNo, order);
		}
		return order;
	}
}
